package com.lzx.applib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.TextView;

import com.lzx.applib.R;
import com.lzx.applib.utils.DpSpDip2Px;

public class HalfRoundText extends TextView {

	int selectedBg;
	int unselectedBg;
	int textSelectedColor;
	int textUnselectedColor;
	int strokeWidth;
    Path path;

	Paint selectPaint;
	Paint unselectPaint;

	public HalfRoundText(Context context) {
		this(context, null);
	}
	
	public HalfRoundText(Context context, AttributeSet attrs) {
		super(context, attrs);

		TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.HalfRoundText);
		selectedBg = array.getColor(R.styleable.HalfRoundText_selectedBg, Color.TRANSPARENT);
		unselectedBg = array.getColor(R.styleable.HalfRoundText_unselectedBg, Color.TRANSPARENT);
		textSelectedColor = array.getColor(R.styleable.HalfRoundText_textSelectedColor, Color.TRANSPARENT);
		textUnselectedColor = array.getColor(R.styleable.HalfRoundText_textUnselectedColor, Color.TRANSPARENT);
		boolean selected = array.getBoolean(R.styleable.HalfRoundText_selected, false);
		array.recycle();
		strokeWidth = 1;
//		strokeWidth = DpSpDip2Px.getInstance().dip2px(1);

		selectPaint = new Paint();
		selectPaint.setColor(selectedBg);
		selectPaint.setAntiAlias(true);
		selectPaint.setStyle(Paint.Style.FILL_AND_STROKE);

		unselectPaint = new Paint();
		unselectPaint.setColor(unselectedBg);
		unselectPaint.setAntiAlias(true);
		unselectPaint.setStyle(Paint.Style.STROKE);
		unselectPaint.setStrokeWidth(strokeWidth);

		setBackgroundColor(Color.TRANSPARENT);
		setGravity(Gravity.CENTER);
        setSelected(selected);
	}


	@Override
	public void setSelected(boolean selected) {
		super.setSelected(selected);
		if (selected) {
			setTextColor(textSelectedColor);
		} else {
			setTextColor(textUnselectedColor);
		}
		invalidate();
	}


	@Override
	protected void onDraw(Canvas canvas) {
		setBackgroundColor(Color.TRANSPARENT);
        canvas.drawPath(getPath(), isSelected() ? selectPaint : unselectPaint);
        super.onDraw(canvas);
	}

	Path getPath() {
		if (path == null) {
			int width = getWidth() - strokeWidth *2;
			int height = getHeight() - strokeWidth *2;
			float hH = height/2f;
			
			path = new Path();
			path.moveTo(hH, 0);
			path.lineTo(width-hH, 0);
			path.arcTo(new RectF(width-height, 0, width, height), -90, 180);
			path.lineTo(hH, height);
			path.arcTo(new RectF(0, 0, height, height), 90, 180);
			path.offset(strokeWidth, strokeWidth);
		}
		return path;
	}
}
